package com.zf.easyexcel.utils.handler;

import com.alibaba.excel.write.handler.SheetWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteWorkbookHolder;
import org.apache.poi.ss.usermodel.Workbook;

import java.util.ArrayList;
import java.util.List;

/**
 * 将表格中 隐藏的sheet 移动到所有sheet的最后面，需要在写入操作的最后使用该处理器
 */
public class MoveHiddenSheetToLastWriteHandler implements SheetWriteHandler {

    @Override
    public void afterSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {
        Workbook workbook = writeWorkbookHolder.getWorkbook();
        // 获取隐藏状态的sheet
        List<String> hiddenSheetList = new ArrayList<>();
        for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
            if (workbook.isSheetHidden(i)) {
                hiddenSheetList.add(workbook.getSheetAt(i).getSheetName());
            }
        }
        // 移动位置
        for (String sheetName : hiddenSheetList) {
            workbook.setSheetOrder(sheetName, workbook.getNumberOfSheets() - 1);
        }
    }

}
